URL = r"http://download.savannah.nongnu.org/releases/openexr/openexr_viewers-%(VERSION)s.tar.gz"
DEFAULT_VERSION = "2.1.0"
VERSIONS = ["2.1.0"]
DEPENDS = ["fltk", "ilmbase", "openexr"]

from source.builders import ConfigureMakeBuilder, VisualStudioBuilder
import os

class OpenExrViewersConfigureMakeBuilder( ConfigureMakeBuilder ):
  """ subclass of ConfigureMakeBuilder with custom configure step """
  def configureparameters(self):
    params = ["--disable-openexrtest", "--disable-openexrctltest"]
    params.append("--with-openexr-prefix="+self.dependencies["openexr"].installpath())
    params.append("--with-fltk-config="+self.dependencies["fltk"].installpath()+os.sep+"bin"+os.sep+"fltk-config")
    ilmbaseincludedir = self.dependencies["ilmbase"].getincludedir()+os.sep+"OpenEXR"
    ilmbaselibdir = self.dependencies["ilmbase"].getlibdir()
    env = os.environ
    env['CPPFLAGS'] = "-I"+ilmbaseincludedir
    env['LDFLAGS'] = "-L"+ilmbaselibdir
    env['LIBS'] = "-lGL -lGLU -lglut"
    return params


class OpenExrViewersWindowsBuilder( VisualStudioBuilder ):


  #def installpath(self):
  #  return os.path.join(self.targetpath(), "bin")

  def make(self):
    os.chdir( self.extractedpath )
    env = os.environ

    #self.debug = False
    #vc9 unavailable so we upgrade the solution vc = {0: "vc8", 1: "vc9"}[self.machine.isVS2008()] 
    debug = {0: "Release", 1: "Debug"}[self.debug]
    
    if self.machine.isVS2008():
      self.execute( "devenv.com vc\\vc8\\OpenEXR_Viewers\\OpenEXR_Viewers.sln /Upgrade" )      
    
    openexrincludedir = self.dependencies["openexr"].getincludedir()+os.sep+"OpenEXR"
    ilmbaseincludedir = self.dependencies["ilmbase"].getincludedir()+os.sep+"OpenEXR"
    fltkincludedir = self.dependencies["fltk"].getincludedir()
    fltklibdir = self.dependencies["fltk"].getlibdir()
    ilmbaselibdir = self.dependencies["ilmbase"].getlibdir()
    openexrlibdir = self.dependencies["openexr"].getlibdir()
    
    if 'INCLUDE' in os.environ.keys():
      env['INCLUDE'] = os.pathsep.join([openexrincludedir, env['INCLUDE']])
    else:
      env['INCLUDE'] = openexrincludedir

    env['INCLUDE'] = os.pathsep.join([ilmbaseincludedir, env['INCLUDE']])
    env['INCLUDE'] = os.pathsep.join([fltkincludedir, env['INCLUDE']])

    if 'LIB' in os.environ.keys():
      env['LIB'] = os.pathsep.join([fltklibdir, env['LIB']])
    else:
      env['LIB'] = fltklibdir

    env['LIB'] = os.pathsep.join([ilmbaselibdir, env['LIB']])
    env['LIB'] = os.pathsep.join([openexrlibdir, env['LIB']])

    replacements = []
    replacements.append(( "#include <FL/Fl.H>", "#define NOMINMAX\n#include <FL/Fl.H>"))
    self.replaceLinesInFile( self.extractedpath+"\\exrdisplay\\main.cpp", replacements )
    
    replacements = []
    replacements.append(( "#include <FL/fl_draw.H>", "#define M_PI 3.14159265358979323846\n#include <FL/fl_draw.H>"))
    self.replaceLinesInFile( self.extractedpath+"\\exrdisplay\\GlWindow3d.cpp", replacements )
        
    replacements = []
    origstring = r'				AdditionalDependencies='
    newstring = r'				AdditionalDependencies="fltk.lib fltkgl.lib IlmImf-2_1.lib IlmThread-2_1.lib Imath-2_1.lib Iex-2_1.lib Half.lib opengl32.lib wsock32.lib comctl32.lib"'
    replacements.append(( origstring, newstring))
    origstring = r'				RelativePath="..\\..\\..\\..\\exrdisplay\\applyCtl.cpp"'
    newstring = r'				RelativePath="..\..\..\..\exrdisplay\GlWindow3d.cpp"></File><File RelativePath="..\..\..\..\exrdisplay\applyCtl.cpp"'
    replacements.append(( origstring, newstring))
    origstring = r'				PreprocessorDefinitions="OPENEXR_DLL;WIN64;NDEBUG;_WINDOWS"'
    newstring = r'				PreprocessorDefinitions="OPENEXR_DLL;WIN64;WIN32;NDEBUG;_WINDOWS"'
    replacements.append(( origstring, newstring))

    self.replaceLinesInFile( self.extractedpath+"\\vc\\vc8\\OpenEXR_Viewers\\exrdisplay\\exrdisplay.vcproj", replacements )

    replacements = []
    origstring = r'set deploypath='
    newstring = r'set deploypath='+self.targetpath()
    replacements.append(( origstring, newstring))
    self.replaceLinesInFile( self.extractedpath+"\\vc\\installexrdisplay.cmd", replacements )

    buildtype = {32 : "Release|win32", 64 : "Release|x64" }    
    buildtype_debug = {32 : "Debug|win32", 64 : "Debug|x64" }
    buildtype_string = ( buildtype[self.machine.bits], buildtype_debug[self.machine.bits] )[self.debug]

    

    self.execute(["devenv.com", "vc\\vc8\\OpenEXR_Viewers\\OpenEXR_Viewers.sln", "/Build", buildtype_string, "/project", "exrdisplay", "/useenv"], env=env )
    
  def install(self ):
    pass

  def copy(self):
    pass

def decider( machine, dirs ):
  return { "Linux" : OpenExrViewersConfigureMakeBuilder,
           "Windows" : OpenExrViewersWindowsBuilder }[machine.platform]

BUILDER = decider


